package ca.turbulent.net
{
	import flash.events.*;
	import flash.net.*;
	import flash.net.registerClassAlias;

	
	public class Remoter extends EventDispatcher
	{
		private var connection			:NetConnection;
		private var service_class		:String;
		private var service_url			:String;
		private var security_token		:String;
		private var secure_connection	:Boolean = false;
		
		public function Remoter(service_url:String, service_class:String)
		{
			this.service_class = service_class;
			this.service_url = service_url;
			
			connection = new NetConnection();
			connection.objectEncoding = ObjectEncoding.AMF0;
			connection.connect(service_url);
			trace("REMOTER - Initialize - "+service_class+"@"+service_url);
		}
		
		public function RegisterClassMapping(mapname:String, classref:Class):void
		{
			registerClassAlias(mapname, classref);	
		}
		
		public function encoding(encode:String):void
		{
			if(encode == 'AMF0')
			connection.objectEncoding = ObjectEncoding.AMF0;
			else
			connection.objectEncoding = ObjectEncoding.AMF3;
		}
		
		
		public function Invoke(functionname:String, responder:Function, fault:Function,  ...args) :void
		{
			var apply_args:Array = new Array();
			apply_args.push(service_class+"."+functionname);
			apply_args.push( new Responder( responder, fault ) );
			
			if(this.secure_connection)
				apply_args.push(this.security_token);
			
			for(var a:int = 0; a < args.length; a++)
			{
				apply_args.push(args[a]);
			}
			trace("REMOTER - Invoke - "+service_class+"."+functionname+"("+args.join(',')+")");
			connection.call.apply(connection, apply_args);
		}
		
		public function RegisterToken(token:String):void
		{
			this.security_token = token;
			secure_connection = true;
		}
		
		public function ClearToken():void
		{
			this.security_token = '';
			this.secure_connection = false;
		}
		
		public function setCredentials(username:String, password:String):void
		{
			connection.addHeader("Credentials", false, {userid:username, password:password});
		}
	}
}